<?php
/**
 * cart.php
 *
 * Cart management
 *
 * @author     Makai Lajos
 * @copyright  2015
 * @license    License.txt
 * @version    2.0
 * @link       http://opencart-api.com/product/opencart-restful-api-pro-v2-0/
 * @see        http://newapi2.opencart-api.com/demo/
 */
require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerRestCart extends RestController {

    private $error = array();

    /*
    * Get cart  点击进货单，查看进货单中的物品
    */
    public function getCart() {
        /*
         * 替换功能，优化执行效率
         * @auther sonicsjh
         */
        //$this->_getCartAfterOptimize();
        //return;
        /**/

        $json = array('success' => true);

        $this->language->load('checkout/cart');

        if (!isset($this->session->data['vouchers'])) {
            $this->session->data['vouchers'] = array();
        }


        if ($this->cart->hasProducts() || !empty($this->session->data['vouchers'])) {

            $points = $this->customer->getRewardPoints();

            $points_total = 0;

            foreach ($this->cart->getProducts() as $product) {
                if ($product['points']) {
                    $points_total += $product['points'];
                }
            }


            if (isset($this->error['warning'])) {
                $data['error_warning'] = $this->error['warning'];
            } elseif (!$this->cart->hasStock() && (!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning'))) {
                $data['error_warning'] = '库存少于您所需要的商品数量或库存不足！';
            } else {
                $data['error_warning'] = '';
            }

            if ($this->config->get('config_customer_price') && !$this->customer->isLogged()) {
                $data['attention'] = sprintf($this->language->get('text_login'), $this->url->link('account/login'), $this->url->link('account/register'));
            } else {
                $data['attention'] = '';
            }

            if ($this->config->get('config_cart_weight')) {
                $data['weight'] = $this->weight->format($this->cart->getWeight(), $this->config->get('config_weight_class_id'), $this->language->get('decimal_point'), $this->language->get('thousand_point'));
            } else {
                $data['weight'] = '';
            }

            $this->load->model('tool/image');
	        $this->load->model('tool/upload');

            $data['products'] = array();

            $products = $this->cart->getProducts();

            foreach ($products as $product) {

                if(isset($this->session->data['sample_checkout'])&&$this->session->data['sample_checkout']==1) {
                    //免费拿样时不做购物车数量检查
                    $minimum_invalide = 0;
                } else {
                    $product_total = 0;

                    foreach ($products as $product_2) {
                        if ($product_2['product_id'] == $product['product_id']) {
                            $product_total += $product_2['quantity'];
                        }
                    }

                    if ($product['minimum'] > $product_total) {
                        $data['error_warning'] = sprintf($this->language->get('error_minimum'), $product['name'], $product['minimum']);
                        $minimum_invalide = 1; 
                    }else{
                        $minimum_invalide = 0; 
                    }

                    if (!isset($product['addnum']) || $product['addnum'] == 0){
                        $product['addnum'] = 1;
                    }
					if ($product_total > $product['minimum'] && ($product_total-$product['minimum']) % $product['addnum'] != 0){
                        $data['error_warning'] = $product['name']."的订单数量不是起批个数的倍数！";
                    }
                }

                if ($product['image']) {
                    $image = $this->model_tool_image->resize($product['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                } else {
                    $image = '';
                }

                $option_data = array();

        		foreach ($product['option'] as $option) {
        			if ($option['type'] != 'file') {
        				$value = $option['value'];
        			} else {
        				$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);

        				if ($upload_info) {
        					$value = $upload_info['name'];
        				} else {
        					$value = '';
        				}
        			}

        			$option_data[] = array(
        				'name'  => $option['name'],
        				'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
        			);
        		}

                // Display prices
                if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                    $price = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $price = false;
                }

                // Display prices
                if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
					$total = $this->currency->format($this->tax->calculate((int)$product['gift_status']?0:$product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity']);
                } else {
                    $total = false;
                }

                $data['products'][] = array(
                    'key'      => isset($product['cart_id']) ? $product['cart_id'] : (isset($product['key']) ? $product['key'] :  ""),
                    'thumb'    => $image,
                    'name'     => $product['name'],
                    'model'    => $product['model'],
                    'product_id'    => $product['product_id'],
                    'option'   => $option_data,
                    'minimum_invalide' =>$minimum_invalide,
                    'quantity' => $product['quantity'],
                    'stock'    => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
                    'reward'   => ($product['reward'] ? sprintf($this->language->get('text_points'), $product['reward']) : ''),
                    'price'    => $price,
                    'total'    => $total,
                    'minimum'  => $product['minimum'],
                    'addnum'   => $product['addnum'],
                    'clearqty'   => $product['clearqty'],
                    'clearance'   => $product['clearance'],
                    'lack_status'   => $product['lack_status'],
                    'lack_reason'   => $product['lack_reason'],
                    'gift_status'=> intval($product['gift_status'])
                );
                $this->load->model('catalog/product');
                $related_product = $this->model_catalog_product->getProductRelated($product['product_id']);
                if($related_product){
                    foreach ($related_product as $key => $value) {
                    if(count($data['related_product']) < 10 && (!in_array($value['product_id'],$related_array))){
                        $data['related_product'][] = $value;
                        $related_array[] = $value['product_id'];
                        }
                    }
                } 
            }

            // Gift Voucher
            $data['vouchers'] = array();

            if (!empty($this->session->data['vouchers'])) {
                foreach ($this->session->data['vouchers'] as $key => $voucher) {
                    $data['vouchers'][] = array(
                        'key'         => $key,
                        'description' => $voucher['description'],
                        'amount'      => $this->currency->format($voucher['amount']),
                        'remove'      => $this->url->link('checkout/cart', 'remove=' . $key)
                    );
                }
            }

                $data['coupon_status'] = $this->config->get('coupon_status');

            if (isset($data['coupon'])) {
                $data['coupon'] = $data['coupon'];			
            } elseif (isset($this->session->data['coupon'])) {
                $data['coupon'] = $this->session->data['coupon'];
            } else {
                $data['coupon'] = '';
            }

            $data['voucher_status'] = $this->config->get('voucher_status');

            if (isset($data['voucher'])) {
                $data['voucher'] = $data['voucher'];				
            } elseif (isset($this->session->data['voucher'])) {
                $data['voucher'] = $this->session->data['voucher'];
            } else {
                $data['voucher'] = '';
            }

            $data['reward_status'] = ($points && $points_total && $this->config->get('reward_status'));

            if (isset($data['reward'])) {
                $data['reward'] = $data['reward'];				
            } elseif (isset($this->session->data['reward'])) {
                $data['reward'] = $this->session->data['reward'];
            } else {
                $data['reward'] = '';
            }

            // Totals
            $this->load->model('extension/extension');

            $total_data = array();
            $total = 0;
            $taxes = $this->cart->getTaxes();

            // Display prices
            if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                $sort_order = array();

                $results = $this->model_extension_extension->getExtensions('total');
                // var_dump( $results);

                foreach ($results as $key => $value) {
                    $sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
                }

                array_multisort($sort_order, SORT_ASC, $results);

                foreach ($results as $result) {
                    // var_dump($result['code'] . '_status');
                    if ($this->config->get($result['code'] . '_status')) {
                        $this->load->model('total/' . $result['code']);
                        // var_dump($result['code']);

                        $this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
                    }
                }

                $sort_order = array();
                // var_dump($total_data);

                foreach ($total_data as $key => $value) {
                    $sort_order[$key] = $value['sort_order'];
                }

                array_multisort($sort_order, SORT_ASC, $total_data);
            }

            $data['totals'] = array();

            foreach ($total_data as $total) {
                $data['totals'][] = array(
                    'title' => $total['title'],
                    'text'  => $this->currency->format($total['value'])
                );
            }

            $json["data"] = $data;


        } else {
            $json["data"] = array();
            // $json['success']    = false;
            // $json['error']['warning']    = '购物车是空的';
        }

        //是否允许首次拿样
        $this->load->model('account/customer');
        $customer_info = $this->model_account_customer->getCustomer($this->customer->getId());
        if(isset($customer_info['sample_bill_amount'])&&$customer_info['sample_bill_amount']!=0) {
            $json["data"]['can_sample_checkout'] = 0;
        } else {
            $json["data"]['can_sample_checkout'] = 1;
        }
        //暂时性禁用免费拿样
        $json["data"]['can_sample_checkout'] = 0;
        
        //当前结账是否为首次拿样
        if(isset($this->session->data['sample_checkout'])&&$this->session->data['sample_checkout']==1) {
            $json["data"]['is_sample_checkout'] = 1;
        }

        //获取用户目前可用优惠券
        //暂时简单处理，找到用户名下第一张可用优惠券
        $avaiable_coupon = $this->model_account_customer->getAvaliableCustomerCoupon($this->customer->getId());
        // var_dump($avaiable_coupon);
        if($avaiable_coupon){
           $json["data"]['avaiable_coupon'] = $avaiable_coupon;
        }
        //标示是否使用优惠券
        if(isset($this->session->data['coupon'])) {
            $json["data"]['coupon_code'] = $this->session->data['coupon'];
        }

        // if(!empty($json["data"]['error_warning'])) {
        //     $json["success"] = false;
        //     $json["error"]['warning'] = $json["data"]['error_warning'];
        // }

		//dyb
		$this->gift_check();

        if ($this->debugIt) {
            echo '<pre>';
            print_r($json);
            echo '</pre>';
        } else {
            $this->response->setOutput(json_encode($json));
        }
    }

    private function validateCoupon($coupon) {
        if(strpos(VERSION, '2.1.') === false){
            $this->load->model('checkout/coupon');
            $this->language->load('checkout/cart');
            $coupon_info = $this->model_checkout_coupon->getCoupon($coupon);
        } else {
            $this->load->model('total/coupon');
            $this->language->load('total/cart');
            $coupon_info = $this->model_total_coupon->getCoupon($coupon);
        }

        if (!$coupon_info) {
            $this->error['warning'] = '未满足优惠券最小使用金额';
        }

        if (!$this->error) {
            return true;
        } else {
            return false;
        }
    }

    private function validateVoucher($voucher) {
        if(strpos(VERSION, '2.1.') === false){
            $this->load->model('checkout/voucher');
            $this->language->load('checkout/cart');
            $voucher_info = $this->model_checkout_voucher->getVoucher($voucher);
        } else {
            $this->load->model('total/voucher');
            $this->language->load('total/cart');
            $voucher_info = $this->model_total_voucher->getVoucher($voucher);
        }

        if (!$voucher_info) {
            $this->error['warning'] = $this->language->get('error_voucher');
        }

        if (!$this->error) {
            return true;
        } else {
            return false;
        }
    }

    private function validateReward($reward) {

        $this->language->load('checkout/cart');
        $points = $this->customer->getRewardPoints();

        $points_total = 0;

        foreach ($this->cart->getProducts() as $product) {
            if ($product['points']) {
                $points_total += $product['points'];
            }
        }

        if (empty($reward)) {
            $this->error['warning'] = $this->language->get('error_reward');
        }

        if ($reward > $points) {
            $this->error['warning'] = sprintf($this->language->get('error_points'), $reward);
        }

        if ($reward > $points_total) {
            $this->error['warning'] = sprintf($this->language->get('error_maximum'), $points_total);
        }

        if (!$this->error) {
            return true;
        } else {
            return false;
        }
    }

    private function validateShipping($shipping_method) {

        $this->language->load('checkout/cart');

        if (!empty($shipping_method)) {
            $shipping = explode('.', $shipping_method);

            if (!isset($shipping[0]) || !isset($shipping[1]) || !isset($this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]])) {
                $this->error['warning'] = $this->language->get('error_shipping');
            }
        } else {
            $this->error['warning'] = $this->language->get('error_shipping');
        }

        if (!$this->error) {
            return true;
        } else {
            return false;
        }
    }

    /*
    * Add item to cart
    */
    public function addToCart($data) {

        $json = $this->addItemCart($data);
		
		//dyb
		$this->gift_check();

        if ($this->debugIt) {
            echo '<pre>';
            print_r($json);
            echo '</pre>';
        } else {
            $this->response->setOutput(json_encode($json));
        }
    }

    /*
    * CART FUNCTIONS
    */
	//购物车分流函数
    public function cart() {

        $this->checkPlugin();
        if($this->customer->getNeedReview()){
            $json['success'] = false;
            $json['error']['warning'] = "用户未审核，不能下单";
            $this->response->setOutput(json_encode($json));
            return;
        }

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            //get cart
            $this->getCart();
        }else if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
            //add to cart
            $requestjson = file_get_contents('php://input');

            $requestjson = json_decode($requestjson, true);

            if ( !empty($requestjson) && $requestjson['show_cart'] == 1) {
                $this->addToCart($requestjson);
            }else {
                $this->response->setOutput(json_encode(array('success' => false)));
            }

        }else if ( $_SERVER['REQUEST_METHOD'] === 'PUT' ){
            //update cart
            $requestjson = file_get_contents('php://input');

            $requestjson = json_decode($requestjson, true);

            //if ( !empty($requestjson) && $requestjson['show_cart'] == 1) {
            if ( !empty($requestjson) ) {
                $this->updateCart($requestjson);
            }else {
                $this->response->setOutput(json_encode(array('success' => false)));
            }

        }else if ( $_SERVER['REQUEST_METHOD'] === 'DELETE' ){
            $requestjson = file_get_contents('php://input');

            $requestjson = json_decode($requestjson, true);

            if ( !empty($requestjson)) {
                $this->deleteCartItem($requestjson);
            }else {
                $this->response->setOutput(json_encode(array('success' => false)));
            }
        }
    }

    /*
    * Delete cart item
    */
    public function deleteCartItem($data) {

        $json = array('success' => true);

        $this->load->model('catalog/product');
        $this->language->load('checkout/cart');
        $id = $data['product_id'];

        //if(isset($this->session->data['cart'][$id])){
        if(!empty($id)){

        $this->cart->remove($id);

		unset($this->session->data['vouchers'][$id]);

		unset($this->session->data['shipping_method']);
		unset($this->session->data['shipping_methods']);
		unset($this->session->data['payment_method']);
		unset($this->session->data['payment_methods']);
		unset($this->session->data['reward']);

		// Totals
		$this->load->model('extension/extension');

		$total_data = array();
		$total = 0;
		$taxes = $this->cart->getTaxes();

		// Display prices
		if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
			$sort_order = array();

			$results = $this->model_extension_extension->getExtensions('total');

			foreach ($results as $key => $value) {
				$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
			}

			array_multisort($sort_order, SORT_ASC, $results);

			foreach ($results as $result) {
				if ($this->config->get($result['code'] . '_status')) {
					$this->load->model('total/' . $result['code']);

					$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
				}
			}

			$sort_order = array();

			foreach ($total_data as $key => $value) {
				$sort_order[$key] = $value['sort_order'];
			}

			array_multisort($sort_order, SORT_ASC, $total_data);
		}

		$json['total'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total));

        }else{
            $json['success'] = false;
            $json['error']['warning']= "没有找到产品ID: ".$id;
        }

		//dyb
		$this->gift_check();

        if ($this->debugIt) {
            echo '<pre>';
            print_r($json);
            echo '</pre>';
        } else {
            $this->response->setOutput(json_encode($json));
        }

    }

    /*
    * Delete cart item by Id
    */
    public function deletecartitembyid() {

        $this->checkPlugin();
        $this->language->load('checkout/cart');
        $json = array('success' => true);

        if ( $_SERVER['REQUEST_METHOD'] === 'DELETE' ){

            $this->load->model('catalog/product');

            $id = 0;

            if (isset($this->request->get['id'])) {
                $id = $this->request->get['id'];
            }

            if(!empty($id)){
                $this->cart->remove($id);

                unset($this->session->data['vouchers'][$id]);

                unset($this->session->data['shipping_method']);
                unset($this->session->data['shipping_methods']);
                unset($this->session->data['payment_method']);
                unset($this->session->data['payment_methods']);
                unset($this->session->data['reward']);

                // Totals
                $this->load->model('extension/extension');

                $total_data = array();
                $total = 0;
                $taxes = $this->cart->getTaxes();

                // Display prices
                if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                    $sort_order = array();

                    $results = $this->model_extension_extension->getExtensions('total');

                    foreach ($results as $key => $value) {
                        $sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
                    }

                    array_multisort($sort_order, SORT_ASC, $results);

                    foreach ($results as $result) {
                        if ($this->config->get($result['code'] . '_status')) {
                            $this->load->model('total/' . $result['code']);

                            $this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
                        }
                    }

                    $sort_order = array();

                    foreach ($total_data as $key => $value) {
                        $sort_order[$key] = $value['sort_order'];
                    }

                    array_multisort($sort_order, SORT_ASC, $total_data);
                }

                $json['total'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total));

            } else{
                $json['success'] = false;
                $json['error'] = "No item found in cart with id: ".$id;
            }
        } else {
            $json["error"]	= "Only DELETE request method allowed";
            $json["success"]	= false;
        }

        $this->sendResponse($json);
    }

    /*	
	* Update item quantity
    */
    private function updateCart( $data) {

        $json = array('success' => true);


        $this->load->model('catalog/product');

        if (!empty($data['quantity'])) {

            foreach ($data['quantity'] as $key => $value) {
                $this->cart->update($key, $value);
            }

	    unset($this->session->data['shipping_method']);
	    unset($this->session->data['shipping_methods']);
	    unset($this->session->data['payment_method']);
	    unset($this->session->data['payment_methods']);
	    unset($this->session->data['reward']);
        } else {
            $json['success']     = false;
            $json['error']['warning'] ="数量不得为空";
        }

		//dyb
		$this->gift_check();

        if ($this->debugIt) {
            echo '<pre>';
            print_r($json);
            echo '</pre>';
        } else {
           $this->response->setOutput(json_encode($json));
        }
    }

    /*
    * Empty cart
    */
    public function emptycart(){

        $this->checkPlugin();

        $json = array('success' => true);

        if ( $_SERVER['REQUEST_METHOD'] === 'DELETE' ){
            $this->cart->clear();
            if ($this->debugIt) {
                echo '<pre>';
                print_r($json);
                echo '</pre>';
            } else {
                $this->response->setOutput(json_encode($json));

            }

        }else {
            $json["error"]	= "Only DELETE request method allowed";
            $json["success"]	= false;
        }
    }

    /*
     * init cart by history orders
     * @author sonicsjh
     */
    public function initCartByHistory(){
        $this->checkPlugin();
        if($this->customer->getNeedReview()){
            $json['success'] = false;
            $json['error']['warning'] = "用户未审核，不能下单";
            $this->response->setOutput(json_encode($json));
            return;
        }

        $this->load->model('checkout/order');
        $historyProducts = $this->model_checkout_order->getHistoryProductsByCustomer();
        //new Array('productId_productOptionId_productOptionValueId' => 'lastOrderId');
        if (false === $historyProducts){
            $json['success'] = false;
            $json['error']['warning'] = "没有历史采购单，一键补货失败";
            $this->response->setOutput(json_encode($json));
            return;
        }

        foreach ($historyProducts['sku'] as $sku=>$orderId){
            $temp = explode('_', $sku);
            $productId = $temp[0];
            $option = array();
            if ('' != $temp[1] && '' !=$temp[2])
                $option[$temp[1]] = $temp[2];
            $this->cart->add($productId, $historyProducts['productMinNum'][$productId], $option);
        }
        $json['success'] = true;
        $this->response->setOutput(json_encode($json));
    }

    /*
     * copy order by orderId
     * @author sonicsjh
     */
    public function copyOrder(){
        $this->checkPlugin();
        if($this->customer->getNeedReview()){
            $json['success'] = false;
            $json['error']['warning'] = "用户未审核，不能下单";
            $this->response->setOutput(json_encode($json));
            return;
        }

        $orderId = (int)$this->request->get['order_id'];
        $this->load->model('checkout/order');
        $historyProducts = $this->model_checkout_order->getOrderProductsByOrderId($orderId);
        if (false === $historyProducts){
            $json['success'] = false;
            $json['error']['warning'] = "没有找到订单信息，复制订单失败";
            $this->response->setOutput(json_encode($json));
            return;
        }
        $this->cart->clear();//强制清空购物车
        foreach ($historyProducts as $sku=>$nums){
            $temp = explode('_', $sku);
            $productId = $temp[0];
            $option = array();
            if ('' != $temp[1] && '' !=$temp[2])
                $option[$temp[1]] = $temp[2];
            $this->cart->add($productId, $nums, $option);
        }
        $json['success'] = true;
        $this->response->setOutput(json_encode($json));
        return true;
    }

    /*
     * replace getCart
     * @author sonicsjh
     */
    protected function _getCartAfterOptimize(){
        if (!$this->customer->isLogged()){
            $data['attention'] = sprintf($this->language->get('text_login'), $this->url->link('account/login'), $this->url->link('account/register'));
        }

        $json = array(
            'success' => true,
            'data' => array(),
        );
        if ($this->cart->hasProducts() || !empty($this->session->data['vouchers'])) {
            $points = $this->customer->getRewardPoints();
            $points_total = 0;
            $data = array(
                'error_warning' => '',
                'attention' => '',
                'weight' => '',
                'products' => array(),
                'vouchers' => array(),
                'coupon_status' => intval($this->config->get('coupon_status')),
                'coupon' => $this->session->data['coupon'],
                'voucher_status' => intval($this->config->get('voucher_status')),
                'voucher' => $this->session->data['voucher'],
                'reward_status' => intval($points && $points_total && $this->config->get('reward_status')),
                'reward' => $this->session->data['reward'],
                'totals' => array(),
                'can_sample_checkout' => 0,//暂时性禁用免费拿样
                'is_sample_checkout' => 0,
                'avaiable_coupon' => array(),
                'coupon_code' => intval($this->session->data['coupon']),
            );
            $dataProducts = $dataVouchers = $dataTotals = array();
            $totalPrice = $totalPoint = 0;

            /* error_warning */
            if (!$this->cart->hasStock() && (!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning'))) {
                $data['error_warning'] = '库存少于您所需要的商品数量或库存不足！'."\r\n";
            }

            /* attention */
            if ($this->config->get('config_customer_price') && !$this->customer->isLogged()) {
                $data['attention'] = sprintf($this->language->get('text_login'), $this->url->link('account/login'), $this->url->link('account/register'));
            }

            /* weight */
            if ($this->config->get('config_cart_weight')) {
                $data['weight'] = $this->weight->format($this->cart->getWeight(), $this->config->get('config_weight_class_id'), $this->language->get('decimal_point'), $this->language->get('thousand_point'));
            }

            /* products */
            $this->load->model('tool/image');
            $this->load->model('tool/upload');
            $cartProducts = $this->cart->getProducts();
            $numsByProductId = array();
            foreach ($cartProducts as $product){
                $numsByProductId[$product['product_id']] += $product['quantity'];
            }
            foreach ($cartProducts as $product){
                /* productImage */
                $productImage = '';
                if ('' != $product['image']){
                    $productImage = $this->model_tool_image->resize($product['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                }

                /* productMinimumInvalide */
                if (intval($this->session->data['sample_checkout']) == 1){//免费拿样时不做购物车数量检查
                    $productMinimumInvalide = 0;
                }else{
                    $product_total = $numsByProductId[$product['product_id']];
                    if ($product['minimum'] > $product_total) {
                        $data['error_warning'] = sprintf($this->language->get('error_minimum'), $product['name'], $product['minimum']);
                        $productMinimumInvalide = 1;
                    }else{
                        $productMinimumInvalide = 0;
                        if ($product['addnum']){
                            if (($product_total-$product['minimum']) % $product['addnum'] != 0){
                                $data['error_warning'] .= $product['name'].'的订单数量不是起批个数的倍数！'."\r\n";//追加warning
                            }
                        }
                    }
                }

                /* productOption */
                $productOption = array();
                foreach ($product['option'] as $option) {
                    if ($option['type'] != 'file'){/* ？？optionType没写全？？*/
                        $value = $option['value'];
                    }else{
                        $upload_info = $this->model_tool_upload->getUploadByCode($option['value']);
                        if ($upload_info){
                            $value = $upload_info['name'];
                        }else{
                            $value = '';
                        }
                    }
                    $productOption[] = array(
                        'name'  => $option['name'],
                        'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
                    );
                }

                /* productPrice & productTotal */
                if ($this->config->get('config_customer_price') || !$this->config->get('config_customer_price')){
                    $productPrice = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
                    if ($product['gift_status']){
                        $productTotal = $this->currency->format($this->tax->calculate(0, $product['tax_class_id'], $this->config->get('config_tax'))* $product['quantity']);
                    }else{
                        $productTotal = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax'))* $product['quantity']);
                    }
                }else{
                    $productPrice = false;
                    $productTotal = false;
                }

                $dataProducts[] = array(
                    'key' => isset($product['cart_id']) ? $product['cart_id'] : (isset($product['key']) ? $product['key'] :  ""),
                    'thumb' => $productImage,
                    'name' => $product['name'],
                    'model' => $product['model'],
                    'product_id' => $product['product_id'],
                    'option' => $productOption,
                    'minimum_invalide' => $productMinimumInvalide,
                    'quantity' => $product['quantity'],
                    'stock' => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
                    'reward' => ($product['reward'] ? sprintf($this->language->get('text_points'), $product['reward']) : ''),
                    'price' => $productPrice,
                    'total' => $productTotal,
                    'minimum' => $product['minimum'],
                    'addnum' => $product['addnum'],
                    'gift_status' => intval($product['gift_status']),
                );
                //$totalPoint += intval($product['points']);
            }
            $data['products'] = $dataProducts;

            /* vouchers */
            if (!empty($this->session->data['vouchers'])) {
                foreach ($this->session->data['vouchers'] as $key => $voucher) {
                    $dataVouchers[] = array(
                        'key' => $key,
                        'description' => $voucher['description'],
                        'amount'  => $this->currency->format($voucher['amount']),
                        'remove'  => $this->url->link('checkout/cart', 'remove=' . $key)
                    );
                }
                $data['vouchers'] = $dataVouchers;
            }

            /* coupon_status */
            //$data['coupon_status'] = $this->config->get('coupon_status');

            /* coupon */
            //if (isset($this->session->data['coupon'])) {
            //    $data['coupon'] = $this->session->data['coupon'];
            //}

            /* voucher_status */
            //$data['voucher_status'] = $this->config->get('voucher_status');

            /* voucher */
            //if (isset($this->session->data['voucher'])) {
            //    $data['voucher'] = $this->session->data['voucher'];
            //}

            /* reward_status */
            //$data['reward_status'] = ($points && $points_total && $this->config->get('reward_status'));

            /* reward */
            //if (isset($this->session->data['reward'])) {
            //    $data['reward'] = $this->session->data['reward'];
            //}

            /* totals */
            if ($this->config->get('config_customer_price') || !$this->config->get('config_customer_price')) {
                $this->load->model('extension/extension');
                $sort_order = $total_data =  array();
                $total = 0;
                $taxes = $this->cart->getTaxes();
                $results = $this->model_extension_extension->getExtensions('total');
                foreach ($results as $key => $value) {
                    $sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
                }
                array_multisort($sort_order, SORT_ASC, $results);

                foreach ($results as $result) {
                    if ($this->config->get($result['code'] . '_status')){
                        $this->load->model('total/' . $result['code']);
                        $this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
                    }
                }

                $sort_order = array();

                foreach ($total_data as $key => $value) {
                    $sort_order[$key] = $value['sort_order'];
                }
                array_multisort($sort_order, SORT_ASC, $total_data);
                foreach ($total_data as $total) {
                    $dataTotals[] = array(
                        'title' => $total['title'],
                        'text'  => $this->currency->format($total['value'])
                    );
                }
            }
            $data['totals'] = $dataTotals;

            /* can_sample_checkout */
            $this->load->model('account/customer');
            /*
            $customer_info = $this->model_account_customer->getCustomer($this->customer->getId());
            if(isset($customer_info['sample_bill_amount'])&&$customer_info['sample_bill_amount']!=0) {
                $data['can_sample_checkout'] = 0;
            } else {
                $data['can_sample_checkout'] = 1;
            }
            */

            /* is_sample_checkout */
            if(intval($this->session->data['sample_checkout']) == 1){
                $data['is_sample_checkout'] = 1;
            }

            /* avaiable_coupon */
            //获取用户目前可用优惠券
            //暂时简单处理，找到用户名下第一张可用优惠券
            $avaiable_coupon = $this->model_account_customer->getAvaliableCustomerCoupon($this->customer->getId());
            if($avaiable_coupon){
                $data['avaiable_coupon'] = $avaiable_coupon;
            }

            /* coupon_code */
            //标示是否使用优惠券
            //if(isset($this->session->data['coupon'])) {
            //    $data['coupon_code'] = $this->session->data['coupon'];
            //}

            $json["data"] = $data;
        }
        //dyb
        $this->gift_check();
        $this->response->setOutput(json_encode($json));
    }

    /*
    * Set Coupon
    */
    public function coupon(){

        $this->checkPlugin();

        $json = array('success' => true);

        if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){

            $requestjson = file_get_contents('php://input');

            $requestjson = json_decode($requestjson, true);
            $post = $requestjson;

            if (isset($post["coupon"]) && $this->validateCoupon($post["coupon"])) {
                $this->session->data['coupon'] = $post["coupon"];
                //$json['message'] = $this->language->get('text_coupon');
                $json['message'] = '成功添加优惠券';
            } else {
                $json['success'] 	= false;
                $json['error'] 		= $this->error;
            }

            if ($this->debugIt) {
                echo '<pre>';
                print_r($json);
                echo '</pre>';
            } else {
                $this->response->setOutput(json_encode($json));
            }

        }else if ( $_SERVER['REQUEST_METHOD'] === 'DELETE' ){
            unset($this->session->data['coupon']);
            // $json['success'] = true;
            $json['message'] = '成功取消优惠券';
            $this->response->setOutput(json_encode($json));
        }else {
            $json["error"]		= "Only POST request method allowed";
            $json["success"]	= false;
        }
    }

    /*
    * Set voucher
    */
    public function voucher(){

        $this->checkPlugin();

        $json = array('success' => true);

        if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){

            $requestjson = file_get_contents('php://input');

            $requestjson = json_decode($requestjson, true);

            $post = $requestjson;

            if (isset($post["voucher"]) && $this->validateVoucher($post["voucher"])) {
                $this->session->data['voucher'] = $post["voucher"];
                $json['message'] = $this->language->get('text_voucher');
            } else {
                $json['error'] 	= $this->error;
                $json['success'] 	= false;
            }

            if ($this->debugIt) {
                echo '<pre>';
                print_r($json);
                echo '</pre>';
            } else {
                $this->response->setOutput(json_encode($json));
            }

        }else {
            $json["error"]		= "Only POST request method allowed";
            $json["success"]	= false;
        }
    }

    /*
    * Set Reward
    */
    public function reward(){

        $this->checkPlugin();

        $json = array('success' => true);

        if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
            $requestjson = file_get_contents('php://input');

            $requestjson = json_decode($requestjson, true);

            $post = $requestjson;

            if (isset($post["reward"]) && $this->validateReward($post["reward"])) {
                $this->session->data['reward'] = abs($post["reward"]);
                $json['message'] = $this->language->get('text_reward');
            } else {
                $json['error'] 	= $this->error;
                $json['success'] 	= false;
            }

            if ($this->debugIt) {
                echo '<pre>';
                print_r($json);
                echo '</pre>';
            } else {
                $this->response->setOutput(json_encode($json));
            }
        }else {
            $json["error"]		= "Only POST request method allowed";
            $json["success"]	= false;
        }
    }

    /*
    * BULK PRODUCT ADD TO CART
    */
    public function bulkcart() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
            $requestjson = file_get_contents('php://input');

            $requestjson = json_decode($requestjson, true);

            if (!empty($requestjson) && count($requestjson) > 0) {

                $this->addItemsToCart($requestjson);
            }else {
                $this->response->setOutput(json_encode(array('success' => false)));
            }

        }else{
            $this->response->setOutput(json_encode(array('success' => false)));
        }
    }

    /*
	Add more item to cart
	*/
    public function addItemsToCart($products) {

        $json = array('success' => true);

        $this->load->model('catalog/product');

        foreach($products as $product) {
            $json = $this->addItemCart($product);
            if($json["success"] == false){
                break;
            }
        }

        if ($this->debugIt) {
            echo '<pre>';
            print_r($json);
            echo '</pre>';
        } else {
            $this->response->setOutput(json_encode($json));
        }

    }

    private function addItemCart($data) {

        $json = array('success' => true);

        $this->language->load('checkout/cart');

        if (isset($data['product_id'])) {
            $product_id = $data['product_id'];
        } else {
            $product_id = 0;
        }
	
        $this->load->model('catalog/product');

        $product_info = $this->model_catalog_product->getProduct($product_id);
	if ($product_info) {
		if (isset($data['quantity'])) {
			$quantity = $data['quantity'];
		} else {
			$quantity = 1;
			$data['quantity'] = 1;
		}
		    
		if (isset($data['option'])) {
			$option = array_filter($data['option']);
		} else {
			$option = array();
		}

		$product_options = $this->model_catalog_product->getProductOptions($data['product_id']);

		foreach ($product_options as $product_option) {
			if ($product_option['required'] && empty($option[$product_option['product_option_id']])) {
				$json['error']['option'][$product_option['product_option_id']] = sprintf($this->language->get('error_required'), $product_option['name']);
				$json['success'] = false;
			}
		}

		if (isset($data['recurring_id'])) {
			$recurring_id = $data['recurring_id'];
		} else {
			$recurring_id = 0;
		}

		$recurrings = $this->model_catalog_product->getProfiles($product_info['product_id']);

		if ($recurrings) {
			$recurring_ids = array();

			foreach ($recurrings as $recurring) {
				$recurring_ids[] = $recurring['recurring_id'];
			}

			if (!in_array($recurring_id, $recurring_ids)) {
				$json['error']['recurring'] = $this->language->get('error_recurring_required');
				$json['success'] = false;
			}
		}

		if ($json['success']) {
			$this->cart->add($data['product_id'], $data['quantity'], $option, $recurring_id);
			
			$json['product']['product_id']	= $product_info['product_id'];
			$json['product']['name']	= isset($product_info['name']) ? $product_info['name'] : "";
			$json['product']['quantity']	= $quantity;

			unset($this->session->data['shipping_method']);
			unset($this->session->data['shipping_methods']);
			unset($this->session->data['payment_method']);
			unset($this->session->data['payment_methods']);

			// Totals
			$this->load->model('extension/extension');

			$total_data = array();
			$total = 0;
			$taxes = $this->cart->getTaxes();

			// Display prices
			if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
				$sort_order = array();

				$results = $this->model_extension_extension->getExtensions('total');

				foreach ($results as $key => $value) {
					$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
				}

				array_multisort($sort_order, SORT_ASC, $results);

				foreach ($results as $result) {
					if ($this->config->get($result['code'] . '_status')) {
						$this->load->model('total/' . $result['code']);

						$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
					}
				}

				$sort_order = array();

				foreach ($total_data as $key => $value) {
					$sort_order[$key] = $value['sort_order'];
				}

				array_multisort($sort_order, SORT_ASC, $total_data);
			}

			$json['total'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total));
		} else {
			$json['success'] = false;
		}

        } else{
            $json['success'] = false;
            $json['error']['warning'] = "商品没有找到";
        }

        return $json;
    }

    public function shippingquotes() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'PUT' ){
            if (isset($this->request->get['id']) && !empty($this->request->get['id'])){
                $this->shipping($this->request->get['id']);
            } else {
                $this->sendResponse(array('success' => false));
            }
        } if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
            $post = file_get_contents('php://input');
            $requestjson = json_decode($post, true);

            if (!empty($requestjson) && count($requestjson) > 0) {
                $this->quote($requestjson);
            }else {
                $this->response->setOutput(json_encode(array('success' => false)));
            }
        }
    }

    public function quote($post) {

        $json = array('success' => true);

        $this->load->language('total/shipping');

        if (!$this->cart->hasProducts()) {
            $json['error']['warning'] = $this->language->get('error_product');
        }

        if (!$this->cart->hasShipping()) {
            $json['error']['warning'] = $this->language->get('error_no_shipping');
        }

        if ($post['country_id'] == '') {
            $json['error']['country'] = $this->language->get('error_country');
        }

        if (!isset($post['zone_id']) || $post['zone_id'] == '') {
            $json['error']['zone'] = $this->language->get('error_zone');
        }

        $this->load->model('localisation/country');

        $country_info = $this->model_localisation_country->getCountry($post['country_id']);

        if ($country_info && $country_info['postcode_required'] && (utf8_strlen(trim($post['postcode'])) < 2 || utf8_strlen(trim($post['postcode'])) > 10)) {
            $json['error']['postcode'] = $this->language->get('error_postcode');
        }

        if (empty($json['error'])) {
            $this->tax->setShippingAddress($post['country_id'], $post['zone_id']);

            if ($country_info) {
                $country = $country_info['name'];
                $iso_code_2 = $country_info['iso_code_2'];
                $iso_code_3 = $country_info['iso_code_3'];
                $address_format = $country_info['address_format'];
            } else {
                $country = '';
                $iso_code_2 = '';
                $iso_code_3 = '';
                $address_format = '';
            }

            $this->load->model('localisation/zone');

            $zone_info = $this->model_localisation_zone->getZone($post['zone_id']);

            if ($zone_info) {
                $zone = $zone_info['name'];
                $zone_code = $zone_info['code'];
            } else {
                $zone = '';
                $zone_code = '';
            }

            $this->session->data['shipping_address'] = array(
                'firstname'      => '',
                'lastname'       => '',
                'company'        => '',
                'address_1'      => '',
                'address_2'      => '',
                'postcode'       => $post['postcode'],
                'city'           => '',
                'zone_id'        => $post['zone_id'],
                'zone'           => $zone,
                'zone_code'      => $zone_code,
                'country_id'     => $post['country_id'],
                'country'        => $country,
                'iso_code_2'     => $iso_code_2,
                'iso_code_3'     => $iso_code_3,
                'address_format' => $address_format
            );

            $quote_data = array();

            $this->load->model('extension/extension');

            $results = $this->model_extension_extension->getExtensions('shipping');

            foreach ($results as $result) {
                if ($this->config->get($result['code'] . '_status')) {
                    $this->load->model('shipping/' . $result['code']);

                    $quote = $this->{'model_shipping_' . $result['code']}->getQuote($this->session->data['shipping_address']);

                    if ($quote) {
                        $quote_data[$result['code']] = array(
                            'title'      => $quote['title'],
                            'quote'      => $quote['quote'],
                            'sort_order' => $quote['sort_order'],
                            'error'      => $quote['error']
                        );
                    }
                }
            }

            $sort_order = array();

            foreach ($quote_data as $key => $value) {
                $sort_order[$key] = $value['sort_order'];
            }

            array_multisort($sort_order, SORT_ASC, $quote_data);

            $this->session->data['shipping_methods'] = $quote_data;

            if ($this->session->data['shipping_methods']) {
                $json['shipping_method'] = $this->session->data['shipping_methods'];
            } else {
                $json['error']['warning'] = sprintf($this->language->get('error_no_shipping'), $this->url->link('information/contact'));
            }
        }

        $this->sendResponse($json);
    }

    public function shipping($shipping_method) {

        $this->load->language('total/shipping');

        $json = array('success' => false);

        if (!empty($shipping_method)) {
            $shipping = explode('.', $shipping_method);

            if (!isset($shipping[0]) || !isset($shipping[1]) || !isset($this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]])) {
                $json['warning'] = $this->language->get('error_shipping');
            }
        } else {
            $json['warning'] = $this->language->get('error_shipping');
        }

        if (empty($json['warning'])) {
            $shipping = explode('.', $shipping_method);

            $this->session->data['shipping_method'] = $this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]];

            $json['success'] = true;
        }

        $this->sendResponse($json);
    }


	//礼品检查
	public function gift_check(){
		
        if(time()+8*60*60 >= strtotime('2017-6-10 00:00:00') && time()+8*60*60 <= strtotime('2017-6-28 23:59:59')){

    		$this->load->model('extension/extension');

    		$total_data = array();
    		$total = 0;
    		$taxes = $this->cart->getTaxes();

    		$sort_order = array();

    		$results = $this->model_extension_extension->getExtensions('total');

    		foreach ($results as $key => $value) {
    			$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
    		}

    		array_multisort($sort_order, SORT_ASC, $results);

    		foreach ($results as $result) {
    			if ($this->config->get($result['code'] . '_status')) {
    				$this->load->model('total/' . $result['code']);

    				$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
    			}
    		}

    		if($total >= 1200 && $total < 3000){
    			
    			$pro_exist = false;
    			$data = array('product_id'=>2999,'quantity'=>1,'option'=>array());
    			foreach ($this->cart->getProducts() as $product) {
    				if($product['product_id'] == '2999'){
                        $id = $product['cart_id'];

                        if(!empty($id)){

                            $this->cart->remove($id);

                            unset($this->session->data['vouchers'][$id]);
                            unset($this->session->data['shipping_method']);
                            unset($this->session->data['shipping_methods']);
                            unset($this->session->data['payment_method']);
                            unset($this->session->data['payment_methods']);
                            unset($this->session->data['reward']);

                        }
                    }
    					

    				if($product['product_id'] == '3000'){

    					$id = $product['cart_id'];

    					if(!empty($id)){

    						$this->cart->remove($id);

    						unset($this->session->data['vouchers'][$id]);
                            unset($this->session->data['shipping_method']);
                            unset($this->session->data['shipping_methods']);
                            unset($this->session->data['payment_method']);
                            unset($this->session->data['payment_methods']);
                            unset($this->session->data['reward']);

    					}

    				}

                    if($product['product_id'] == '3001'){

                        $id = $product['cart_id'];

                        if(!empty($id)){

                            $this->cart->remove($id);

                            unset($this->session->data['vouchers'][$id]);
                            unset($this->session->data['shipping_method']);
                            unset($this->session->data['shipping_methods']);
                            unset($this->session->data['payment_method']);
                            unset($this->session->data['payment_methods']);
                            unset($this->session->data['reward']);

                        }

                    }
    				//增加更多代码.....
    			}

    			$this->addItemCart($data);

    		}elseif($total >= 3000 && $total < 5000){
    			
    			$pro_exist = false;
    			$data = array('product_id'=>3000,'quantity'=>1,'option'=>array());
    			foreach ($this->cart->getProducts() as $product) {
    				if($product['product_id'] == '3000'){
                        $id = $product['cart_id'];

                        if(!empty($id)){

                            $this->cart->remove($id);

                            unset($this->session->data['vouchers'][$id]);
                            unset($this->session->data['shipping_method']);
                            unset($this->session->data['shipping_methods']);
                            unset($this->session->data['payment_method']);
                            unset($this->session->data['payment_methods']);
                            unset($this->session->data['reward']);

                        }
                    }
    					

    				if($product['product_id'] == '2999'){

    					$id = $product['cart_id'];

    					if(!empty($id)){

    						$this->cart->remove($id);

    						unset($this->session->data['vouchers'][$id]);
                            unset($this->session->data['shipping_method']);
                            unset($this->session->data['shipping_methods']);
                            unset($this->session->data['payment_method']);
                            unset($this->session->data['payment_methods']);
                            unset($this->session->data['reward']);

    					}

    				}

                    if($product['product_id'] == '3001'){

                        $id = $product['cart_id'];

                        if(!empty($id)){

                            $this->cart->remove($id);

                            unset($this->session->data['vouchers'][$id]);
                            unset($this->session->data['shipping_method']);
                            unset($this->session->data['shipping_methods']);
                            unset($this->session->data['payment_method']);
                            unset($this->session->data['payment_methods']);
                            unset($this->session->data['reward']);

                        }

                    }
    				//增加更多代码.....
    			}
    			
    			$this->addItemCart($data);

    		}elseif($total >= 5000){

                $pro_exist = false;
                $data = array('product_id'=>3001,'quantity'=>1,'option'=>array());
                foreach ($this->cart->getProducts() as $product) {
                    if($product['product_id'] == '3001'){
                        $id = $product['cart_id'];

                        if(!empty($id)){

                            $this->cart->remove($id);

                            unset($this->session->data['vouchers'][$id]);
                            unset($this->session->data['shipping_method']);
                            unset($this->session->data['shipping_methods']);
                            unset($this->session->data['payment_method']);
                            unset($this->session->data['payment_methods']);
                            unset($this->session->data['reward']);

                        }
                    }
                        

                    if($product['product_id'] == '2999'){

                        $id = $product['cart_id'];

                        if(!empty($id)){

                            $this->cart->remove($id);

                            unset($this->session->data['vouchers'][$id]);
                            unset($this->session->data['shipping_method']);
                            unset($this->session->data['shipping_methods']);
                            unset($this->session->data['payment_method']);
                            unset($this->session->data['payment_methods']);
                            unset($this->session->data['reward']);

                        }

                    }

                    if($product['product_id'] == '3000'){

                        $id = $product['cart_id'];

                        if(!empty($id)){

                            $this->cart->remove($id);

                            unset($this->session->data['vouchers'][$id]);
                            unset($this->session->data['shipping_method']);
                            unset($this->session->data['shipping_methods']);
                            unset($this->session->data['payment_method']);
                            unset($this->session->data['payment_methods']);
                            unset($this->session->data['reward']);

                        }

                    }
                    //增加更多代码.....
                }

                $this->addItemCart($data);

    		}else{

                foreach ($this->cart->getProducts() as $product) {

                    if($product['product_id'] == '2999'){

                        $id = $product['cart_id'];

                        if(!empty($id)){

                            $this->cart->remove($id);

                            unset($this->session->data['vouchers'][$id]);
                            unset($this->session->data['shipping_method']);
                            unset($this->session->data['shipping_methods']);
                            unset($this->session->data['payment_method']);
                            unset($this->session->data['payment_methods']);
                            unset($this->session->data['reward']);

                        }

                    }
                    
                    if($product['product_id'] == '3000'){

                        $id = $product['cart_id'];

                        if(!empty($id)){

                            $this->cart->remove($id);

                            unset($this->session->data['vouchers'][$id]);
                            unset($this->session->data['shipping_method']);
                            unset($this->session->data['shipping_methods']);
                            unset($this->session->data['payment_method']);
                            unset($this->session->data['payment_methods']);
                            unset($this->session->data['reward']);

                        }

                    }

                    if($product['product_id'] == '3001'){

                        $id = $product['cart_id'];

                        if(!empty($id)){

                            $this->cart->remove($id);

                            unset($this->session->data['vouchers'][$id]);
                            unset($this->session->data['shipping_method']);
                            unset($this->session->data['shipping_methods']);
                            unset($this->session->data['payment_method']);
                            unset($this->session->data['payment_methods']);
                            unset($this->session->data['reward']);

                        }

                    }
                    //增加更多代码.....
                }

            }
        }else{

            foreach ($this->cart->getProducts() as $product) {

                if($product['product_id'] == '2999'){

                    $id = $product['cart_id'];

                    if(!empty($id)){

                        $this->cart->remove($id);

                        unset($this->session->data['vouchers'][$id]);
                        unset($this->session->data['shipping_method']);
                        unset($this->session->data['shipping_methods']);
                        unset($this->session->data['payment_method']);
                        unset($this->session->data['payment_methods']);
                        unset($this->session->data['reward']);

                    }

                }
                
                if($product['product_id'] == '3000'){

                    $id = $product['cart_id'];

                    if(!empty($id)){

                        $this->cart->remove($id);

                        unset($this->session->data['vouchers'][$id]);
                        unset($this->session->data['shipping_method']);
                        unset($this->session->data['shipping_methods']);
                        unset($this->session->data['payment_method']);
                        unset($this->session->data['payment_methods']);
                        unset($this->session->data['reward']);

                    }

                }

                if($product['product_id'] == '3001'){

                    $id = $product['cart_id'];

                    if(!empty($id)){

                        $this->cart->remove($id);

                        unset($this->session->data['vouchers'][$id]);
                        unset($this->session->data['shipping_method']);
                        unset($this->session->data['shipping_methods']);
                        unset($this->session->data['payment_method']);
                        unset($this->session->data['payment_methods']);
                        unset($this->session->data['reward']);

                    }

                }
                //增加更多代码.....
            }
        }
	}
}